package pub.cleangao.memm.util;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.security.Security;


public class AES {

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
    private static final byte[] iv = {
            (byte) 'c', (byte) 'l', (byte) 'e', (byte) 'a',
            (byte) 'n', (byte) 'g', (byte) 'a', (byte) 'o',
            (byte) 'g', (byte) 'i', (byte) 'v', (byte) 'e',
            (byte) 'y', (byte) 'o', (byte) 'u', (byte) 'p'};

    static {
        Security.addProvider(new BouncyCastleProvider());
    }


    public static byte[] encrypt(byte[] content, String password) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM,"BC");
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password),new IvParameterSpec(iv));
        return cipher.doFinal(content);
    }


    public static byte[] decrypt(byte[] content, String password) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM,"BC");
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password),new IvParameterSpec(iv));
        return cipher.doFinal(content);
    }


    private static SecretKeySpec getSecretKey(String password) throws Exception {
        KeyGenerator kg = null;
        kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kg.init(128, random);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
    }


}